import numpy as np
import matplotlib.pyplot as plt
from chaco.api import *
from traits.api import *
from traitsui.api import *
from enable.api import ComponentEditor
def pd(pfa0, pd0, r0 , rcs0, N,r, rcs):
    t=pfa0**(-1/N)-1
    print(t)
    sn0= (t/(pd0**(-1/N)-1)-1)
    print(sn0)
    cs = (sn0*(r0**4))/rcs0
    print(cs)
    sn = cs*rcs/(r**4)
    pd = (1+t/(1+sn))**(-N)
    return pd


class Pd(HasTraits):
    pfa0 = Range(low=0.0, high=1.0, value=0.1) #给定点虚警概率
    pd0 = Range(low=0.0, high=1.0, value=0.95)  # 给定点探测概率
    r0 = Float(5)
    rcs0 = Float(1)
    N = Float(4)  # 恒虚警处理器数目
    rcs = Float(10)
    data = Property(Array, observe=['pfa0','pd0','r0','rcs0','N','rcs'])
    plot_left = Instance(Plot)

    def _plot_left_default(self):
        r = np.arange(2, 202,2)
        PD = pd(self.pfa0, self.pd0, self.r0 , self.rcs0, self.N, r, self.rcs)
        plot = Plot(ArrayPlotData(R=r, E1=PD))
        plot.title = 'Detection probability'
        plot.x_axis.title = "distance /km"
        plot.y_axis.title = "Detection probability"
        plot.plot(("R", "E1"), name='目标探测概率', color=palette11[0])

        return plot

    def _get_data(self):
        data={}
        r = np.arange(5, 1005,5)
        PD = pd(self.pfa0, self.pd0, self.r0 , self.rcs0, self.N,r, self.rcs)
        data['r']=r
        data['e1'] = PD
        return data

    @observe("data")
    def _update_plot_left(self, event):
        self.plot_left.data.update_data(
            T=self.data['r'],
            E1=self.data['e1'],
        )

    traits_view = View(
        Group(
            HGroup(
                UItem(
                    "plot_left",
                    editor=ComponentEditor(),
                    resizable=True
                ),

            ),
        ),
        Item('pfa0', label='参考目标虚警概率', editor_args={'mode': 'slider'}),
        Item('pd0', label='参考目标探测概率', editor_args={'mode': 'slider'}),
        Item('r0', label='参考目标距离'),
        Item('rcs0', label='参考目标雷达散射截面'),
        Item('N', label='恒虚警处理器数目'),
        Item('rcs', label='目标雷达散射截面'),
    )

class Form(HasTraits):
    Pd = Instance(Pd, ())
    traits_view = View(
        Tabbed(
            UItem('Pd', style='custom', label='探测概率'),

        ),
        title='生存力计算',
        width=1200,
        height=800,
        resizable=True,
    )

if __name__ == '__main__':
    Form().configure_traits()
